package com.example.mobifin_busticket.views.activities;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.AppPreferences;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.R.id;
import com.example.mobifin_busticket.R.layout;
import com.example.mobifin_busticket.R.menu;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.models.TicketDetailsModel;
import com.example.mobifin_busticket.views.adapter.CustommenuListAdapter;
import com.example.mobifin_busticket.views.dialogs.BoadingPointDetailsDialog;
import com.example.mobifin_busticket.views.dialogs.CancellationPolicy;
import com.example.mobifin_busticket.views.dialogs.PassenegerDetailsDialog;
import com.example.mobifin_busticket.views.dialogs.SendEmailDialog;
import com.example.mobifin_busticket.views.dialogs.SendSmsDilaog;
import com.example.mobifin_busticket.views.dialogs.TermsAndCondtionDialog;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TicketBookingSummaryScreen extends MobifinActivity implements
		OnClickListener {
	TextView tvTicketStatus, tvFromName, tvTovalue, tvBusType, tvseatname,
			tvPassengerName, tvTicketNo, tvTravelName, tvBoedingPOint,
			tvTravellerContactNo, tvPNRNo, tvTotalFare, tvDepartureTime,
			tvReportingTime, tvdepartureTimeForReporting,
			tvBoardingDetailsButton, tvTermsCondition, trvelPhNo,
			tvMorePassengerDetails, tvAgentName, tvAgentPhoneNo, tvAgetEmail,
			tvCancellationPolicy;
	ArrayList<TicketDetailsModel> ticketDetailsList;
	SimpleDateFormat simpledateformatIssue = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");
	ArrayList<TicketDetailsModel> inventoryList;
	Button btnHeaderBack, btn_userSelectMenu;
	SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat formatterissue = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
	TicketDetailsModel ticketDetailsModel;
	String DepartureTime, formatededDate = "", PickupLoction,
			pickUpLocationLandMark, pickULocationAddress, stremailsub;;
	Long pickUpTime;
	String strTicketNo, tag, strPassengerPhNo, strPassengerEmail,
			strCancellationPolicy;
	boolean partialCancellationAllowed;
	ListView llMenuList;
	CustommenuListAdapter listAdapter;
	private static final String HMAPPMFORMAT = "hh:mm a";
	String fontsize = "4";
	String trclose = "</tr>";
	String tdclose = "</td>";
	String brclose = "<br />";
	SimpleDateFormat cancelpolicyformatter = new SimpleDateFormat("hh:mm a");
	DateFormat cancelpolicydfYmm = new SimpleDateFormat("yyyy-MM-dd");
	String cancelstrHour, cancelstrMin, cancelstrAmpm, strHour, strMin,
			strAmpm;
	ArrayList<String> sepratedCancellationList = new ArrayList<String>();
	List<String> arrcancelledpolicyColon = new ArrayList<String>();
	Map<String, String> mcancelpolicyHashMap = null;
	List<Map<String, String>> mainHasmapPlociy = new ArrayList<Map<String, String>>();

	private static final String STRDASH = "--------------------------------\n";
	private static final String STRSPACE = "          ";
	Date doj, cancelticketdateDoj;;
	String strongtagfont = "<strong><strong><font size=";
	List<String> tempRate;
	List<String> tempPolicyDates;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ticket_booking_summary_screen);
		tvAgentName = (TextView) findViewById(R.id.tvAgentName);
		tvAgentPhoneNo = (TextView) findViewById(R.id.tvAgentPhoneNo);
		tvAgetEmail = (TextView) findViewById(R.id.tvAgetEmail);
		tvTicketStatus = (TextView) findViewById(R.id.tvTicketStatus);
		tvDepartureTime = (TextView) findViewById(R.id.tvDepartureTime);
		tvReportingTime = (TextView) findViewById(R.id.tvReportingTime);
		tvdepartureTimeForReporting = (TextView) findViewById(R.id.tvdepartureTimeForReporting);
		tvFromName = (TextView) findViewById(R.id.tvFromName);
		tvTovalue = (TextView) findViewById(R.id.tvTovalue);
		tvTravelName = (TextView) findViewById(R.id.tvTravelName);
		trvelPhNo = (TextView) findViewById(R.id.trvelPhNo);
		tvBusType = (TextView) findViewById(R.id.tvBusType);
		tvseatname = (TextView) findViewById(R.id.tvseatname);
		tvPassengerName = (TextView) findViewById(R.id.tvPassenger);
		tvTravellerContactNo = (TextView) findViewById(R.id.tvtravellercontactNo);
		tvMorePassengerDetails = (TextView) findViewById(R.id.tvMorePassengerDetails);
		tvBoedingPOint = (TextView) findViewById(R.id.tvBoedingPOint);
		tvBoardingDetailsButton = (TextView) findViewById(R.id.tvBoardingDetailsButton);
		tvTicketNo = (TextView) findViewById(R.id.tvTicketNo);
		tvPNRNo = (TextView) findViewById(R.id.tvPNRNo);
		tvTotalFare = (TextView) findViewById(R.id.tvTotalFare);
		tvTermsCondition = (TextView) findViewById(R.id.tvTermsCondition);
		tvCancellationPolicy = (TextView) findViewById(R.id.tvCancellationPolicy);
		llMenuList = (ListView) findViewById(R.id.llMenuList);
		btnHeaderBack = (Button) findViewById(R.id.btnHeaderBack);
		btn_userSelectMenu = (Button) findViewById(R.id.btn_userSelectMenu);
		tvCancellationPolicy.setOnClickListener(this);
		btn_userSelectMenu.setOnClickListener(this);
		btnHeaderBack.setOnClickListener(this);
		tvMorePassengerDetails.setOnClickListener(this);
		tvTermsCondition.setOnClickListener(this);
		tvBoardingDetailsButton.setOnClickListener(this);
		ticketDetailsList = new ArrayList<TicketDetailsModel>();
		inventoryList = new ArrayList<TicketDetailsModel>();
		ticketDetailsList = AppData.ticketDetailsList;
		ticketDetailsModel = new TicketDetailsModel();
		tag = getIntent().getStringExtra("TAG");
		if (tag.equalsIgnoreCase("FromPinConfirm")) {
			setValue(ticketDetailsList);
		} else if (tag.equalsIgnoreCase("PrintTicket")) {
			strTicketNo = getIntent().getStringExtra("TicketNo");
			getTicketDetailsForPrintTicketDialog();

		}

		ArrayList<String> listValue = new ArrayList<String>();
		listValue.add(getResources().getString(R.string.email_ticket));
		listValue.add(getResources().getString(R.string.sms_ticket));
		listAdapter = new CustommenuListAdapter(
				TicketBookingSummaryScreen.this, R.layout.custom_menu_list,
				listValue);
		llMenuList.setAdapter(listAdapter);
		llMenuList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				onMenuItemClick(position);
			}
		});

	}

	private void getTicketDetailsForPrintTicketDialog() {
		// TODO Auto-generated method stub
		ResponseListener ticketDetailsResponseFromSeatSeller = new ResponseListener() {
			@Override
			public void onResponse(Object objTicketDetails) {
				// TODO Auto-generated method stub
				ArrayList<TicketDetailsModel> ticketDetailsList = (ArrayList<TicketDetailsModel>) objTicketDetails;
				System.out.println("Ticket Details:" + objTicketDetails);
				setValue(ticketDetailsList);

			}
		};

		// TODO Auto-generated method stub
		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.getTicketDetails(TicketBookingSummaryScreen.this,
				ticketDetailsResponseFromSeatSeller, AppData.CONSUMERKEY,
				AppData.SECRETKEY, AppData.BASESEATURL + "/ticket?tin="
						+ strTicketNo, "TicketDetails");

	}

	private void setValue(ArrayList<TicketDetailsModel> ticketDetailsList) {
		// TODO Auto-generated method stub
		for (int i = 0; i < ticketDetailsList.size(); i++) {
			inventoryList = ticketDetailsList.get(i).getinventoryList();
			strCancellationPolicy = ticketDetailsList.get(i)
					.getcancellationPolicy();
			partialCancellationAllowed = ticketDetailsList.get(i)
					.getpartialCancellationAllowed();
			DepartureTime = ticketDetailsList.get(i).getdoj();
			formatededDate = getFormatedDepartureTime(DepartureTime);
			PickupLoction = ticketDetailsList.get(i).getpickupLocation();
			pickUpLocationLandMark = ticketDetailsList.get(i)
					.getpickupLocationLandmark();
			pickULocationAddress = ticketDetailsList.get(i)
					.getpickUpLocationAddress();

			pickUpTime = Long.parseLong(ticketDetailsList.get(i)
					.getpickupTime());
			tvdepartureTimeForReporting
					.setText(convertTimeto12hourfmt(pickUpTime));
			tvReportingTime
					.setText(convertTimeReport(tvdepartureTimeForReporting
							.getText().toString().trim()));
			tvDepartureTime.setText(Html.fromHtml(getApplicationContext()
					.getResources().getString(R.string.travelling)
					+ " "
					+ formatededDate));
			tvTicketStatus.setText(ticketDetailsList.get(i).getstatus());
			tvFromName.setText(ticketDetailsList.get(i).getsourceCity());
			tvTovalue.setText(ticketDetailsList.get(i).getdestinationCity());
			tvTravelName.setText(ticketDetailsList.get(i).gettravels());
			tvBusType.setText(ticketDetailsList.get(i).getbusType());
			tvseatname.setText(ticketDetailsList.get(i).getTDseatName());

			tvPassengerName.setText(ticketDetailsList.get(i).gettravellerName()
					+ " " + ticketDetailsList.get(i).getgender());
			tvTravellerContactNo.setText(ticketDetailsList.get(i).getphno());
			strPassengerPhNo = ticketDetailsList.get(i).getphno();
			strPassengerEmail = ticketDetailsList.get(i).getEmailId();
			tvBoedingPOint
					.setText(ticketDetailsList.get(i).getpickupLocation());
			tvTicketNo.setText(ticketDetailsList.get(i).gettin());
			tvPNRNo.setText(ticketDetailsList.get(i).getpnr());
			tvTotalFare
					.setText("INR " + ticketDetailsList.get(i).getSeatFare());

			forNullField(ticketDetailsList);
		}

	}

	private void forNullField(ArrayList<TicketDetailsModel> ticketDetailsList) {
		// TODO Auto-generated method stub

		for (int i = 0; i < ticketDetailsList.size(); i++) {
			if (ticketDetailsList.get(i).getinventoryList().size() > 1) {
				inventoryList = ticketDetailsList.get(i).getinventoryList();
				tvMorePassengerDetails.setVisibility(View.VISIBLE);

			} else {
				tvMorePassengerDetails.setVisibility(View.GONE);
			}
		}
	}

	private CharSequence convertTimeReport(String time) {
		// TODO Auto-generated method stub
		String actultime = null;
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(HMAPPMFORMAT);
			Date date = formatter.parse(time);
			Calendar repotCal = Calendar.getInstance();
			repotCal.set(Calendar.HOUR, date.getHours());
			repotCal.set(Calendar.MINUTE, date.getMinutes());
			repotCal.add(Calendar.MINUTE, -15);
			actultime = formatter.format(repotCal.getTime());
		} catch (Exception e) {
			Log.e(AppData.EXCEPTION, e.getMessage(), e);
		}
		return actultime;
	}

	private CharSequence convertTimeto12hourfmt(Long pickUpTime) {
		// TODO Auto-generated method stub
		String actultime;
		int quotient, hour, minitue;
		quotient = (int) (pickUpTime / 60);
		minitue = (int) (pickUpTime % 60);
		hour = quotient % 24;
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minitue);
		Date mDate = new Date(c.getTimeInMillis());
		DateFormat dateFormat = new SimpleDateFormat(HMAPPMFORMAT);
		actultime = dateFormat.format(mDate);
		return actultime;
	}

	private String getFormatedDepartureTime(String departureTime) {
		// TODO Auto-generated method stub
		String monthName = "", dayName = "";
		String strdoj;
		try {
			Date date = simpledateformat.parse(departureTime);
			SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
			monthName = monthDate.format(date.getTime());

			SimpleDateFormat sdf = new SimpleDateFormat("EEE");
			dayName = sdf.format(date);
		} catch (java.text.ParseException e) {
			Log.e(AppData.EXCEPTION, e.toString(), e);
		}
		strdoj = dayName
				+ ","
				+ departureTime.substring(Math.max(departureTime.length() - 2,
						0)) + " " + monthName + " "
				+ departureTime.substring(0, 4).toString();
		return strdoj;
	}

	protected void onMenuItemClick(int position) {
		// TODO Auto-generated method stub
		ticketDetailsList = AppData.ticketDetailsList;
		String tagval = "";
		if (position == 0) {

			tagval = tag + ";" + AppData.EMAILID;
			if (tvTicketStatus.getText().toString().equals("CANCELLED")) {
				stremailsub = AppData.CANCELLATIONSUB;
			} else {
				stremailsub = AppData.BOOKINGSUB;
			}
			SendEmailDialog emailDialog = new SendEmailDialog(
					TicketBookingSummaryScreen.this, strPassengerEmail,
					stremailsub, setEmailMessage(ticketDetailsList), tagval,
					" " + ";" + " ");
			emailDialog.show();
		}
		if (position == 1) {
			tagval = tag + ";" + AppData.SMSBODY;
			SendSmsDilaog smsDialog = new SendSmsDilaog(
					TicketBookingSummaryScreen.this, " ", " ", " ", tagval,
					setSMS(ticketDetailsList));
			smsDialog.show();
		}
	}

	void clearPlicyArrays() { // TODO Auto-generated method stub
		if (mainHasmapPlociy != null) {
			mainHasmapPlociy.clear();
		}
		if (sepratedCancellationList != null) {
			sepratedCancellationList.clear();
		}
		if (arrcancelledpolicyColon != null) {
			arrcancelledpolicyColon.clear();
		}

	}

	private String setSMS(ArrayList<TicketDetailsModel> ticketDetailsList) {
		// TODO Auto-generated method stub
		System.out.println("Inventory size:" + inventoryList.size());
		String strSMS;
		String seatname = "";
		String temseat = "";
		for (int i = 0; i < inventoryList.size(); i++) {
			seatname = inventoryList.get(i).getTDseatName();

			if (i == inventoryList.size() - 1) {
				temseat = temseat + seatname;
			} else {
				temseat = temseat + seatname + ",";
			}
		}
		if (tvTicketStatus.getText().toString().equals("CANCELLED")) {
			strSMS = inventoryList.get(1).getphno() + ";" + strTicketNo + " ("
					+ temseat + ") " + "This Ticket has been Cancelled.";
		} else {
			strSMS = inventoryList.get(0).getphno()
					+ ";"
					+ "Dear, "
					+ inventoryList.get(0).gettravellerName()
					+ ", your pnr: "
					+ tvPNRNo.getText().toString().trim()
					+ ", journey: from "
					+ tvTovalue.getText().toString().trim()
					+ " to "
					+ tvFromName.getText().toString().trim()
					+ ", seat: "
					+ temseat
					+ " date: "
					+ simpledateformat
							.format(mconvertStringtoDoj(DepartureTime))
					+ tvDepartureTime.getText().toString().trim()
					+ " is booked.Thanks";
		}

		return strSMS;
	}

	private Date mconvertStringtoDoj(String strDate) {

		Date dateobj = null;
		try {
			dateobj = simpledateformat.parse(strDate);
		} catch (ParseException e) {
			Log.d(AppData.ERROR, e.toString(), e);
		}
		return dateobj;
	}

	private String setEmailMessage(
			ArrayList<TicketDetailsModel> ticketDetailsList) {
		// TODO Auto-generated method stub
		String seatname = "";
		String temseat = "";
		String policy = "";
		String allow = "";
		String emailmsg = "";
		String passengerName = null, fare = null, passengerMobileNo = null, passengerEmail = null, PickUpTime = null, DateOfIssue = null;
		Boolean cancellationAllow = null;
		String strMainPolicy = null, strDepartuurTime, strDOJ = null;
		// clearPlicyArrays();
		for (int j = 0; j < ticketDetailsList.size(); j++) {
			passengerName = ticketDetailsList.get(j).getinventoryList().get(0)
					.gettravellerName();
			cancellationAllow = ticketDetailsList.get(j)
					.getpartialCancellationAllowed();
			fare = ticketDetailsList.get(j).getSeatFare();
			passengerMobileNo = ticketDetailsList.get(j).getinventoryList()
					.get(0).getphno();
			passengerEmail = ticketDetailsList.get(j).getinventoryList().get(0)
					.getEmailId();
			PickUpTime = ticketDetailsList.get(j).getpickupTime();
			DateOfIssue = ticketDetailsList.get(j).getdateOfIssue();
			strMainPolicy = ticketDetailsList.get(j).getcancellationPolicy();
			strDOJ = ticketDetailsList.get(j).getdoj();

		}

		for (int i = 0; i < inventoryList.size(); i++) {
			seatname = inventoryList.get(i).getTDseatName();

			if (i == inventoryList.size() - 1) {
				temseat = temseat + seatname;
			} else {
				temseat = temseat + seatname + ",";
			}
		}

		if (cancellationAllow == true) {
			policy = "*Partial Cancellation Is Allowed";
			allow = "Allowed";
		} else {
			policy = "*Partial Cancellation Is Not Allowed";
			allow = "Not Allowed";
		}

		try {
			mSummaryCancelData(strMainPolicy, strDOJ);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String tabelDaynamic = mTableHtml();
		emailmsg = "<html>" + "<head>" + "<title></title>" + "</head>"
				+ "<body>" + "<p>" + "<font size="
				+ fontsize
				+ "><strong>Hi Dear </strong></font><font size="
				+ fontsize
				+ ">"
				+ passengerName
				+ "</font> <strong>,</strong></p>"
				+ "<p>"
				+ "<font size="
				+ fontsize
				+ ">Please Find Your Booking Detail As Below.........</font> </p>"
				+ "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" height=\"263\" width=\"800\">"
				+ "<caption>"
				+ brclose
				+ "<strong>Booking Information</strong><br />"
				+ "<strong>Agent Name</strong><strong> : </strong>"
				+ tvAgentName.getText().toString().trim()
				+ brclose
				+ "<strong>Agent Email</strong><strong> : </strong>"
				+ tvAgetEmail.getText().toString().trim()
				+ brclose
				+ "<strong>Agent Phone</strong><strong> : </strong>"
				+ tvAgentPhoneNo.getText().toString().trim()
				+ brclose
				+ "<strong>(<strong>Journey Date</strong> : </strong>"
				+ formatededDate
				+ "<strong>)<br />"

				+ "(</strong>"
				+ tvTovalue.getText().toString().trim()
				+ "<strong> <strong>To</strong> </strong>"
				+ tvFromName.getText().toString().trim()
				+ "<strong>)</strong></caption>"
				+ "<tbody>"
				+ "<tr>"
				+ "<td>"
				+ "<strong>Passanger Name : </strong>"
				+ passengerName
				+ tdclose
				+ "<td>"
				+ "<strong>PNR : </strong>"
				+ tvPNRNo.getText().toString().trim()
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Ticket Number : </strong>"
				+ tvTicketNo.getText().toString().trim()
				+ tdclose
				+ "<td>"
				+ "<strong>Travels : </strong>"
				+ tvTravelName.getText().toString().trim()
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Seat : </strong>"
				+ temseat
				+ tdclose
				+ "<td>"
				+ "<strong>Total Fare ("
				+ AppData.CURRENCY
				+ ") :</strong>"
				+ fare
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Bus Type : </strong>"
				+ tvBusType.getText().toString().trim()
				+ tdclose
				+ "<td>"
				+ "<strong>Travel Contact No:</strong>"
				+ tvTravellerContactNo.getText().toString().trim()
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Passenger Mobile No : </strong>"
				+ passengerMobileNo
				+ tdclose
				+ "<td>"
				+ " <strong>Email : </strong>"
				+ passengerEmail
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Pickup Up Time : </strong>"
				+ PickUpTime
				+ tdclose
				+ "<td>"
				+ " <strong>Reporting Time : </strong>"
				+ tvReportingTime.getText().toString().trim()
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Date Of Journey : </strong>"
				+ formatededDate
				+ tdclose
				+ "<td>"
				+ "<strong>Date Of Booking : </strong>"
				+ formatterissue.format(mconvertStringtoDate(DateOfIssue))
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Departure Time : </strong>"
				+ tvDepartureTime.getText().toString().trim()
				+ tdclose
				+ "<td>"
				+ "<strong>Partial Cancellation Allowed : </strong>"
				+ allow
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Boarding Point : </strong>"
				+ tvBoedingPOint.getText().toString().trim()
				+ tdclose
				+ "<td>"
				+ "<strong>Status : </strong>"
				+ tvTicketStatus.getText().toString().trim()
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td colspan=\"2\">"
				+ "<table  style=border-left:0px>"
				+ "<tr>"
				+ "<td>"
				+ "<strong>Cancellation Policy : </strong>"
				+ tdclose
				+ trclose
				+ "<tr>"
				+ "<td>"
				+ "<strong>Cancellation Time</strong>"
				+ tdclose
				+ "<td>"
				+ "<strong>Charges</strong>"
				+ tdclose
				+ trclose
				+ tabelDaynamic
				+ "</table>"
				+ "<strong>"
				+ policy
				+ "</strong>"
				+ tdclose
				+ trclose
				+

				"</tbody>"
				+ "</table>"
				+ "<p>"
				+ strongtagfont
				+ fontsize
				+ ">Terms and conditions </strong></strong></p>"
				+ "<p>"
				+ AppData.SHOPNAMETERMSEMAIL
				+ " is only a bus ticket agent. It does not operate bus services of its own."
				+ " In order to provide a comprehensive choice of bus operators, departure times and prices to "
				+ "customers, "
				+ "it has tied up with many bus operators."
				+ AppData.SHOPNAMETERMSEMAIL
				+ " advice to customers is to choose bus"
				+ " operators they are aware of and whose service they are comfortable with.</font></p>"
				+ "     <p class=\"p0\" style=\"margin-bottom:0pt; margin-top:0pt; \">"
				+ "<strong><span style=\"font-weight: bold; font-size: 12pt; font-family: Arial; "
				+ "background: rgb(253, 253, 253);\">As&nbsp;per&nbsp;Government&nbsp;norm&nbsp;extra&nbsp;service&nbsp;"
				+ "tax&nbsp;is&nbsp;applicable&nbsp;on&nbsp;A/C&nbsp;buses.</span></strong><span style=\"font-weight:"
				+ " bold; font-size: 12pt;\"><o:p></o:p></span></p>"
				+ "     <p>"
				+ strongtagfont
				+ fontsize
				+ ">Any issues or grievances related to travel or operator will be entertained within"
				+ " 10 days of post journey. In any case the liability will not be more than the ticket fare.</font></strong>"
				+ "</strong></p>"
				+ "     <p>"
				+ strongtagfont
				+ fontsize
				+ ">"
				+ AppData.SHOPNAMETERMSEMAIL
				+ " is responsible for</strong></strong><br />"
				+ "(1) Issuing a valid ticket (a ticket that will be accepted by the bus operator) for its network of bus operators.<br />"
				+ "(2) Providing refund and support in the event of cancellation<br />"
				+ "(3) Providing customer support and information in case of any delays / inconvenience</font></p>"
				+ "<p>"
				+ strongtagfont
				+ fontsize
				+ ">"
				+ AppData.SHOPNAMETERMSEMAIL
				+ " is not responsible for</strong></strong><br />"
				+ "(1) The bus operator&#39;s bus not departing / reaching on time<br />"
				+ "(2) The bus operator&#39;s employees being rude<br />"
				+ "(3) The bus operator&#39;s bus seats etc not being up to the customers expectation<br />"
				+ "(4) The bus operator canceling the trip due to unavoidable reasons</font></p>"
				+ "</body>" + "</html>";

		return emailmsg;
	}

	private void mSummaryCancelData(String strMainPolicy, String strDOJ)
			throws ParseException {
		// TODO Auto-generated method stub
		tempPolicyDates = new ArrayList<String>();
		tempRate = new ArrayList<String>();
		if (tempRate != null) {
			tempRate.clear();
		}
		if (tempPolicyDates != null) {
			tempPolicyDates.clear();
		}
		String strPolicy[] = strMainPolicy.split(";");

		for (int i = 0; i < strPolicy.length; i++) {
			sepratedCancellationList.add(strPolicy[i]);
			System.out.println("new string at: " + i + ": " + strPolicy[i]);
		}

		getHourMinfromDept();
		String strsepratebySemi = sepratedCancellationList.toString()
				.replace("[", "").replace("]", "");
		Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
		List<String> seperateArr = null;

		String[] mainStrtoStore = strsepratebySemi.split(",");
		conditionForPolicy(TicketBookingSummaryScreen.this, mainStrtoStore,
				seperateArr, map);
	}

	private String conditionForPolicy(
			TicketBookingSummaryScreen ticketBookingSummaryScreen,
			String[] mainStrtoStore, List<String> seperateArr,
			Map<Integer, List<String>> map) {
		// TODO Auto-generated method stub
		List<String> mseperateArr = seperateArr;
		for (int j = 0; j < mainStrtoStore.length; j++) {
			arrcancelledpolicyColon.add(mainStrtoStore[j]);
		}
		for (int k = 0; k < arrcancelledpolicyColon.size(); k++) {
			Log.d("mai", "" + arrcancelledpolicyColon.get(k));

			String[] mai = arrcancelledpolicyColon.get(k).split(":");
			Log.d("maiLentght", "" + mai.length);
			mseperateArr = new ArrayList<String>();
			for (int m = 0; m < mai.length; m++) {
				mseperateArr.add(mai[m]);
			}
			Log.d("seperateArrseperateArrseperateArr", "" + mseperateArr);
			map.put(k, mseperateArr);
		}
		for (int i = 0; i < map.size(); i++) {
			insidemainloginloop(i, map);
		}
		Log.d("Finally", mainHasmapPlociy.toString());

		/*
		 * for (int i = 0; i < mainHasmapPlociy.size(); i++) {
		 * showCancelationpolicy(i, context); }
		 */
		String poStringpolicy = "";
		for (int i = 0; i < mainHasmapPlociy.size(); i++) {
			poStringpolicy = poStringpolicy + showCancelationpolicysum(i);
		}
		Log.e("tempPolicy", "" + poStringpolicy);
		return poStringpolicy;
	}

	private String showCancelationpolicysum(int i) {
		// TODO Auto-generated method stub
		String strbookTempPolicy = "";

		if (i == mainHasmapPlociy.size() - 1) {
			strbookTempPolicy = Html.fromHtml(getResources().getString(
					R.string.before)
					+ mainHasmapPlociy.get(i).get("betweentime"))
					+ " ";
			strbookTempPolicy = strbookTempPolicy + " ["
					+ (mainHasmapPlociy.get(i).get("rate") + "%") + "]" + "\n";
			tempPolicyDates.add("<b>Before&nbsp;</b>"
					+ mainHasmapPlociy.get(i).get("betweentime") + " ");

		} else {
			strbookTempPolicy = Html.fromHtml(getResources().getString(
					R.string.betweeen)
					+ mainHasmapPlociy.get(i).get("betweentime")
					+ " "
					+ getResources().getString(R.string.and)
					+ mainHasmapPlociy.get(i).get("starttime"))
					+ "";
			strbookTempPolicy = strbookTempPolicy + " ["
					+ (mainHasmapPlociy.get(i).get("rate") + "%") + "]" + "\n";
			tempPolicyDates.add("<b>Between&nbsp;</b>"
					+ mainHasmapPlociy.get(i).get("betweentime") + " "
					+ "<b>And&nbsp;</b>"
					+ mainHasmapPlociy.get(i).get("starttime") + "");
		}

		tempRate.add("<b>" + mainHasmapPlociy.get(i).get("rate") + "%"
				+ "&nbsp;</b>");

		return strbookTempPolicy;
	}

	private void insidemainloginloop(int i, Map<Integer, List<String>> map) {
		// TODO Auto-generated method stub
		Log.d(" map.size()", "" + map.size());
		Log.d("Inside value", "" + map.get(i));
		List<String> temparr = new ArrayList<String>();
		temparr = map.get(i);
		Log.d(" temparr size", "" + temparr.size());

		for (int j = 0; j < temparr.size(); j++) {
			if (seperatePlcydata(i, map, temparr)) {
				break;
			}
		}
	}

	private boolean seperatePlcydata(int i, Map<Integer, List<String>> map,
			List<String> temparr) {
		// TODO Auto-generated method stub
		boolean isBreak = false;
		Log.d("insidede i value ", "" + i);
		if (i == map.size() - 1) {
			Log.d("insidede ", "minue 12313");
			if (("-1").equalsIgnoreCase(temparr.get(1).trim())) {
				Log.d("going in minus one", "minus");
				Calendar cal = Calendar.getInstance(); // creates
				cal.setTime(cancelticketdateDoj);
				cal.add(Calendar.AM_PM, Integer.parseInt(strAmpm));
				cal.add(Calendar.HOUR,
						-Integer.parseInt(temparr.get(0).trim().toString()));
				mcancelpolicyHashMap = new HashMap<String, String>();
				if (mcancelpolicyHashMap != null) {
					mcancelpolicyHashMap.clear();
				}
				mcancelpolicyHashMap.put("starttime", "");
				mcancelpolicyHashMap.put("betweentime",
						formatter.format(cal.getTime()));
				mcancelpolicyHashMap.put("rate",
						temparr.get(temparr.size() - 2));
				mcancelpolicyHashMap.put("absolute",
						temparr.get(temparr.size() - 1));
				mainHasmapPlociy.add(mcancelpolicyHashMap);
				isBreak = true;
			}
		} else if (("0").equals(temparr.get(0).trim())) {
			Log.d("Between 0", "Between");
			Calendar cal = Calendar.getInstance(); // creates
			// calendar
			cal.setTime(cancelticketdateDoj);
			cal.add(Calendar.AM_PM, Integer.parseInt(strAmpm));
			cal.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(1).trim().toString()));
			Calendar calDoj = Calendar.getInstance(); // creates
			// calendar
			calDoj.setTime(cancelticketdateDoj);
			calDoj.add(Calendar.AM_PM, Integer.parseInt(strAmpm));
			mcancelpolicyHashMap = new HashMap<String, String>();
			if (mcancelpolicyHashMap != null) {
				mcancelpolicyHashMap.clear();
			}
			mcancelpolicyHashMap.put("starttime",
					formatter.format(calDoj.getTime()));
			mcancelpolicyHashMap.put("betweentime",
					formatter.format(cal.getTime()));
			mcancelpolicyHashMap.put("rate", temparr.get(temparr.size() - 2));
			mcancelpolicyHashMap.put("absolute",
					temparr.get(temparr.size() - 1));
			mainHasmapPlociy.add(mcancelpolicyHashMap);
			isBreak = true;
		} else {
			Calendar cal = Calendar.getInstance(); // creates
			Calendar cal2 = Calendar.getInstance(); // creates
			cal.setTime(cancelticketdateDoj);
			cal.add(Calendar.AM_PM, Integer.parseInt(strAmpm));
			cal.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(0).trim().toString()));
			cal2.setTime(cancelticketdateDoj);
			cal2.add(Calendar.AM_PM, Integer.parseInt(strAmpm));
			cal2.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(1).trim().toString()));
			mcancelpolicyHashMap = new HashMap<String, String>();
			if (mcancelpolicyHashMap != null) {
				mcancelpolicyHashMap.clear();
			}
			mcancelpolicyHashMap.put("starttime",
					formatter.format(cal.getTime()));
			mcancelpolicyHashMap.put("betweentime",
					formatter.format(cal2.getTime()));
			mcancelpolicyHashMap.put("rate", temparr.get(temparr.size() - 2));
			mcancelpolicyHashMap.put("absolute",
					temparr.get(temparr.size() - 1));
			mainHasmapPlociy.add(mcancelpolicyHashMap);
			isBreak = true;
		}
		return isBreak;
	}

	private void getHourMinfromDept() {
		// TODO Auto-generated method stub
		Date strDept;
		try {
			strDept = cancelpolicyformatter.parse(tvdepartureTimeForReporting
					.getText().toString());
			String strDeptime = formatter.format(strDept);
			Log.e("strDeptime", "" + strDeptime);
			String[] strDeptimearr = strDeptime.split(" ");
			String strDeptimearrHm = strDeptimearr[1];
			String[] strDeptimearrHmSplit = strDeptimearrHm.split(":");
			strHour = strDeptimearrHmSplit[0];
			strMin = strDeptimearrHmSplit[1];
			Log.e("hourmin", "" + strHour + "--?>" + strMin);
			if (strDeptimearr[2].contains("AM")) {
				strAmpm = "0";
			} else {
				strAmpm = "1";
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			cancelticketdateDoj = cancelpolicydfYmm.parse(DepartureTime);
			cancelticketdateDoj.setHours(Integer.parseInt(strHour));
			cancelticketdateDoj.setMinutes(Integer.parseInt(strMin));
			Log.e("DateOf join", "" + formatter.format(cancelticketdateDoj));
		} catch (ParseException e1) {

		}
	}

	private Date mconvertStringtoDate(String strDate) {

		Date dateobj = null;
		try {
			dateobj = simpledateformatIssue.parse(strDate);
		} catch (ParseException e) {
			Log.d(AppData.ERROR, e.toString(), e);
		}
		return dateobj;
	}

	private String mTableHtml() {
		String strPolicyEmail = "";
		for (int i = 0; i < tempRate.size(); i++) {
			strPolicyEmail = strPolicyEmail + "<tr>" + "<td>"
					+ tempPolicyDates.get(i) + tdclose + "<td>"
					+ tempRate.get(i) + tdclose + trclose;

		}
		Log.d("strPolicyEmail", "" + strPolicyEmail);
		return strPolicyEmail;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tvBoardingDetailsButton:
			Util.mListHide(llMenuList);
			onClickBoardingDetails();
			break;

		case R.id.tvTermsCondition:
			Util.mListHide(llMenuList);
			onClickTermsAndCondition();
			break;
		case R.id.tvMorePassengerDetails:
			Util.mListHide(llMenuList);
			onClickPassengerDetails();
			break;
		case R.id.btnHeaderBack:
			finish();
			break;
		case R.id.btn_userSelectMenu:

			Util.onClickUserMenu(TicketBookingSummaryScreen.this, llMenuList);
			break;
		case R.id.tvCancellationPolicy:
			onClickCancellationPOlicy();
			break;
		default:
			break;
		}
	}

	private void onClickCancellationPOlicy() {
		// TODO Auto-generated method stub
		CancellationPolicy cancellationPolicyDialog = new CancellationPolicy(
				TicketBookingSummaryScreen.this, tvdepartureTimeForReporting
						.getText().toString().trim(), strCancellationPolicy,
				DepartureTime, partialCancellationAllowed);
		cancellationPolicyDialog.show();
	}

	private void onClickPassengerDetails() {
		// TODO Auto-generated method stub
		PassenegerDetailsDialog passengerDialog = new PassenegerDetailsDialog(
				TicketBookingSummaryScreen.this, inventoryList);
		passengerDialog.show();
	}

	private void onClickTermsAndCondition() {
		// TODO Auto-generated method stub
		TermsAndCondtionDialog termsAndConditonDialog = new TermsAndCondtionDialog(
				TicketBookingSummaryScreen.this);
		termsAndConditonDialog.show();

	}

	private void onClickBoardingDetails() {
		// TODO Auto-generated method stub

		BoadingPointDetailsDialog boardingDetailsDialod = new BoadingPointDetailsDialog(
				TicketBookingSummaryScreen.this, PickupLoction,
				pickUpLocationLandMark, pickULocationAddress);
		boardingDetailsDialod.show();
	}

}
